﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Logistics.WebApi.Controllers
{
    public class CommonController : System.Web.Http.ApiController
    {
        /// <summary>
        /// WebAPI实现文件上传
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadImage()
        {
            var content = Request.Content;
            var uploadDir = System.Web.HttpContext.Current.Server.MapPath("~/Upload");
            var newFileName = "";
            var sp = new MultipartMemoryStreamProvider();
            Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();

            foreach (var item in sp.Contents)
            {
                if (item.Headers.ContentDisposition.FileName != null)
                {
                    var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                    newFileName = uploadDir + "\\" + filename;
                    var ms = item.ReadAsStreamAsync().Result;
                    using (var br = new BinaryReader(ms))
                    {
                        var data = br.ReadBytes((int)ms.Length);
                        File.WriteAllBytes(newFileName, data);
                    }
                }
            }
            var result = new Dictionary<string, string>();
            result.Add("result", newFileName);
            var resp = Request.CreateResponse(HttpStatusCode.OK, result);
            resp.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
            return resp;
        }
    }
}